/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.zzdt4j.common.extension.spi;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Dynamic thread-pool SPI service loader
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @see ServiceLoader
 * @since 2023/10/11 1:41
 */
public class ServiceLoaderRegistry {

    private static final Map<Class<?>, Collection<?>> SERVICES = new ConcurrentHashMap<>();

    private ServiceLoaderRegistry() {
    }

    /**
     * register
     *
     * @param serviceInterface serviceInterface
     */
    public static void register(final Class<?> serviceInterface) {
        if (!SERVICES.containsKey(serviceInterface)) {
            SERVICES.put(serviceInterface, load(serviceInterface));
        }
    }

    /**
     * load
     *
     * @param serviceInterface service-interface
     * @param <T>              serviceInterface
     * @return SPI class
     */
    private static <T> Collection<T> load(final Class<T> serviceInterface) {
        Collection<T> result = new LinkedList<>();
        for (T each : ServiceLoader.load(serviceInterface)) {
            result.add(each);
        }
        return result;
    }

    public static <T> Collection<T> getServiceInstances(final Class<T> serviceClass) {
        return null == serviceClass.getAnnotation(SingletonSPI.class) ? newServiceInstances(serviceClass) : getSingletonServiceInstances(serviceClass);
    }

    @SuppressWarnings("unchecked")
    public static <T> Collection<T> getSingletonServiceInstances(Class<T> serviceClass) {
        return (Collection<T>) SERVICES.getOrDefault(serviceClass, Collections.emptyList());
    }

    @SuppressWarnings("unchecked")
    private static <T> Collection<T> newServiceInstances(Class<T> serviceClass) {
        return SERVICES.containsKey(serviceClass) ? SERVICES.get(serviceClass).stream().map(
                each -> (T) newServiceInstance(each.getClass())).collect(Collectors.toList()) : Collections.emptyList();
    }

    private static Object newServiceInstance(Class<?> aClass) {
        try {
            return aClass.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new ServiceLoaderInstantiationException(aClass, e);
        }
    }
}
